import Vue from 'vue'
import request from './request'

// 标准方式 使用无问题
export class Store {
  constructor(data = []) {
    this.view = Vue.observable({
      data,
      page: 1,
      pageSize: 10,
      total: 0,
      status: 0,
      loading: false
    })
    this.controller = null
  }

  async loadData(params) {
    // 上一个请求可以取消 并且 请求为完成
    if (this.controller || this.loading) {
      this.controller.abort()
    }
    this.controller = new AbortController()
    const signal = this.controller.signal

    this.status = 1
    this.loading = true

    try {
      const { data } = await request.get(this.url, {
        ...params,
        signal
      })

      if (this.getSuccess(data)) {
        // 修改状态码
        this.status = 2
        // 修改请求状态
        this.loading = false
        // 修改数据状态
        Object.assign(this.view, {
          data: this.getData(data),
          page: this.getPage(data),
          pageSize: this.getPageSize(data),
          total: this.getTotal(data)
        })
      }
    } catch (error) {
      // 请求失败需要给出空数据保证插槽提示的正确性 并且提供默认状态
      Object.assign(this.view, {
        data: this.getData(),
        page: this.getPage(),
        pageSize: this.getPageSize(),
        total: this.getTotal()
      })

      this.status = 3
      this.loading = false
    }
  }
  // 取消请求
  abort() {
    if (this.controller) {
      this.controller.abort()
    }
  }

  // 复用axios成功解析逻辑
  getSuccess(res) {
    return res?.status === 200
  }
  getData(res) {
    return res?.data?.data || []
  }
  getPage(res) {
    return res?.data?.page || 1
  }
  getPageSize(res) {
    return res?.data?.pageSize || 10
  }
  getTotal(res) {
    return res?.data?.total || 0
  }

  get loading() {
    return this.view.loading
  }
  set loading(newVal) {
    this.view.loading = newVal
  }
  get status() {
    return this.view.status
  }
  set status(newVal) {
    this.view.status = newVal
  }
}

export class Model {
  constructor(data = {}) {
    this.view = Vue.observable({
      data
    })
  }

  // 查指定数据
  async findData(id) {
    this.status = 1
    this.loading = true
    try {
      const { data } = await request.get(this.proxy.action.findDataUrl)
      if (data.status === 200) {
        this.status = 2
        this.data = data.data
      }
    } catch (e) {
      this.status = 3
      console.log(e)
    }
  }
  // 新增数据
  async editorData(params) {
    this.status = 1
    this.loading = true
    try {
      const { data } = await request.get(this.proxy.action.findDataUrl, { params })
      if (data.status === 200) {
        this.status = 2
        this.data = data.data
      }
    } catch (e) {
      this.status = 3
      console.log(e)
    }
  }

  get data() {
    return this.view.data
  }
  set data(newVal) {
    this.view.data = newVal
  }
}
